import sys
import random
import pygame
from pygame.math import Vector2

"""
一：
1、生成操作框
    1、操作框大小、初始化坐标、单元格大小等
    2、操作框标题、颜色等
2、贪吃蛇
    1、绘制贪吃蛇，初始化大小，坐标、颜色等
    2、定义贪吃蛇能力，上下左右移动、吃水果、死亡限制等
3、水果
    1、绘制水果，大小、坐标（随机生产）、颜色等
4、校验吃到水果、校验死亡限制
5、退出等

二、
1、水果大小、颜色随机（有限制），吃水果后增长长度不一
"""
# 屏幕颜色
screen_color = (0, 0, 0)
# 单元格大小
cell_size = 20
cell_num = 20

pygame.init()
# 标题
pygame.display.set_caption("贪吃蛇")
# 屏幕大小
screen = pygame.display.set_mode((cell_num * cell_size, cell_num * cell_size))
clock = pygame.time.Clock()

USER_KEY_EVENT = pygame.USEREVENT
# 设置事件轮训时间
pygame.time.set_timer(USER_KEY_EVENT, 400)

fruit_color = (126, 166, 114)  # 水果颜色


class Fruit:
    """水果"""

    def __init__(self):
        self.randomize()

    def randomize(self):
        """随机位置"""
        self.x = random.randint(1, cell_num - 2)
        self.y = random.randint(1, cell_num - 2)
        # self.color = (255, 0, 0)
        self.pos = Vector2(self.x, self.y)
        self.random_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        self.random_size = random.randrange(cell_size, 3 * cell_size, cell_size)

    def draw(self):
        """在图上绘制水果"""
        fruit_rect = pygame.Rect(self.x * cell_size, self.y * cell_size, self.random_size, self.random_size)
        pygame.draw.rect(screen, self.random_color, fruit_rect)


snake_color = (183, 111, 122)  # 蛇体颜色


class Snake:
    """贪吃蛇对象"""

    def __init__(self):
        # 初始🐍
        self.body = [Vector2(5, 10), Vector2(4, 10), Vector2(3, 10)]
        self.direction = Vector2(1, 0)

    def draw(self):
        """在图上绘制🐍"""
        for block in self.body:
            x_pos = int(block.x * cell_size)
            y_pos = int(block.y * cell_size)
            block_rect = pygame.Rect(x_pos, y_pos, cell_size, cell_size)
            pygame.draw.rect(screen, snake_color, block_rect)

    def move(self):
        """移动🐍
            先缩减原body最后一个位置，再添加新的位置
        """
        self.body.pop()
        self.body.insert(0, self.body[0] + self.direction)

    def eat(self, size):
        """吃到水果,头部增加"""
        for i in range(size):
            self.body.insert(0, self.body[0] + self.direction)


def game_over():
    """游戏结束"""
    pygame.quit()
    sys.exit()


class Main:
    """主体类"""

    def __init__(self):
        """初始化 蛇、水果"""
        self.snake = Snake()
        self.fruit = Fruit()

    def draw_elements(self):
        """绘制元素"""
        self.fruit.draw()
        self.snake.draw()

    def check_touch(self):
        """检查吃到水果"""
        # 超出多单位后，判断接触逻辑要修改
        size = self.get_change_size()
        touch_list = [self.fruit.pos]
        if size > 1:
            size = size-1
            touch_list.append(self.fruit.pos + Vector2(size, 0))
            touch_list.append(self.fruit.pos + Vector2(0, size))
            touch_list.append(self.fruit.pos + Vector2(size, size))
        if touch_list.count(self.snake.body[0]) > 0:
            print('吃到了水果,位置是：{}'.format(self.fruit.pos))
            print('吃到了水果,蛇位置是：{}'.format(self.snake.body[0]))
            print('吃到了水果,位置列表是：{}'.format(touch_list))
            self.fruit.randomize()
            self.snake.eat(size)

    def check_fail(self):
        """检查死亡限制"""
        if not 0 <= self.snake.body[0].x < cell_num or not 0 <= self.snake.body[0].y < cell_num:
            print('撞墙了,位置是：{}'.format(self.snake.body[0]))
            game_over()

    def update_draw(self):
        """更新画面"""
        self.snake.move()
        self.check_touch()
        self.check_fail()

    def get_change_size(self):
        """获取改变大小"""
        return self.fruit.random_size // cell_size
main = Main()

while True:
    """循环游戏事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over()
        if event.type == USER_KEY_EVENT:
            main.update_draw()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if main.snake.direction.y != 1:
                    main.snake.direction = Vector2(0, -1)
            if event.key == pygame.K_DOWN:
                if main.snake.direction.y != -1:
                    main.snake.direction = Vector2(0, 1)
            if event.key == pygame.K_LEFT:
                if main.snake.direction.x != 1:
                    main.snake.direction = Vector2(-1, 0)
            if event.key == pygame.K_RIGHT:
                if main.snake.direction.x != -1:
                    main.snake.direction = Vector2(1, 0)

    # 屏幕颜色
    main.draw_elements()
    pygame.display.update()
    screen.fill(screen_color)
    clock.tick(60)
